package server.networking;

/**
 * The PolicyGetter class retrieves the client.policy and server.policy
 * files from the root of the project and returns the absolute path of
 * either one of these files.
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

public class PolicyGetter {

	/**
	 * Finds the absolute path of the policy file (client or server) and returns
	 * it as a string to the calling method.
	 * @param type Either "server" or "client"
	 * @return The absolute path of the policy file.
	 */
	
	public static String getPolicyLocation(String type) {
		String policyRelativeLocation = "/" + type + ".policy";
		
		try {
			File tempFile = File.createTempFile(type, ".policy");
			InputStream is = PolicyGetter.class.getResourceAsStream(policyRelativeLocation);
			BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
			int nextByte = 0;
			while ((nextByte = is.read()) != -1) {
				writer.write(nextByte);
			}
			writer.close();
			tempFile.deleteOnExit();
			return tempFile.getAbsolutePath();
		}
		catch (IOException e) {
			System.out.println("An error occurred.");
			e.printStackTrace();
			return null;
		}
	}
}
